package com.xiaogao.common.exception;

import com.xiaogao.common.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e) {
        log.error("未知异常:", e);
        return Result.failed(500, e.getMessage());
    }

    // 业务异常拦截
    @ExceptionHandler(BusinessException.class)
    public Result<String> handleBusinessException(BusinessException e) {
        log.error("业务异常:{}", e.getMessage());
        return Result.failed(e.getCode(), e.getMessage());
    }

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handleException(MethodArgumentNotValidException e) {
        StringBuilder errorBuilder = new StringBuilder();
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for (ObjectError allError : allErrors) {
            FieldError fieldError = (FieldError) allError;
            String fieldName = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            log.info("field={},message={}", fieldName, message);
            String errorMsg = String.format("字段：%s%s", fieldName, message);
            errorBuilder.append(errorMsg).append("<br>");
        }
        return Result.failed(400, errorBuilder.toString());
    }
}
